import { AvatarDropdown, AvatarName } from '@/components';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { PageLoading, SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { netConfig } from './requestErrorConfig';



import { SearchButton } from './components/RightContent';
import { getUserInfoUsingGet } from './services/novel-web/userController';

import { USER_DEFAULT_AVATAR } from './models/constant';


// const variable
const isDev = process.env.NODE_ENV === 'development';
// const loginPath = '/user/login';


/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.UserVO;
  loading?: boolean;
  // fetchUserInfo?: () => Promise<API.UserVO | undefined>;
}> {

  console.debug("getInitialState()");
    
  try {
    const req = await getUserInfoUsingGet();

    console.debug(JSON.stringify(req.data));

    if(req.data){
      return {
        currentUser: req.data,
        settings: defaultSettings as Partial<LayoutSettings>, 
      }
    }
  } catch (error) {
    // ignore error
  }
  
  return {
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}


// ProLayout 支持的api https://procomponents.ant.design/components/layout
// ./config/defaultSetting.ts
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    // 页面顶部栏右侧 的小按钮中的文档 和 语言切换
    // actionsRender: () => [<Question key="doc" />, <SelectLang key="SelectLang" />],
    actionsRender: ()=>[<SearchButton key='search'/>],
    avatarProps: {
      src: initialState?.currentUser?.avatar ?? USER_DEFAULT_AVATAR,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown menu={true} >{avatarChildren}</AvatarDropdown>;
      },
    },
    //水印设置
    waterMarkProps: {
      // content: initialState?.currentUser?.name,
    },
    footerRender: false,
    onPageChange: () => {
      // 如果没有登录，且现在不是登录页，重定向到 loginPage  (一定要登录才能访问其他页面)
      //const { location } = history;
      // if (!initialState?.currentUser && location.pathname !== LOGIN_ROUTE_PATH) {
      //   history.push(LOGIN_ROUTE_PATH);
      // }
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    links: isDev
      ? [
          // <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
          //   <LinkOutlined />
          //   <span>OpenAPI 文档</span>
          // </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    pageTitleRender: false,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      if (initialState?.loading) return <PageLoading />;
      return (
        <div className='layout-container'
          style={{display: 'flex',flexDirection:'column',minHeight:'84vh'}}
        >
          <div className='content' style={{flex:1,padding:'10px'}}>
            {children}
          </div>
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
          

              
        </div>
        
        
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...netConfig,
};
